<template>
	<div class="list">
		<div class="title" @click="more = !more">{{title}}<span v-if="datas.length > 14" :class="more ? 'icon xiangshang' : 'icon xiangxia'"></span></div>
		<div v-if="unlimited" @click="clear" class="item" :class="{active: isEmpty}">不限</div>
		<div v-for="(item,index) in datas" :key="index" v-if="index<14 || more" class="item" :class="{active: isSelected(item)}" @click="change(item)">{{item[titleName]}}</div>
		<div v-if="datas.length > 14" class="more" @click="more = !more"><span :class="more ? 'icon xiangshang' : 'icon xiangxia'"></span></div>
	</div>
</template>

<script>
export default {
	props: {
		title: String,
		datas: Array,
		prop: String,
		value: Object,
		unlimited: {
			type: Boolean,
			default: true
		},
		multiple: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			more : false,
			keyName:'key',
			titleName:'title'
		}
	},
	mounted() {
		if(this.datas[0].id && this.datas[0].name){
			this.keyName = 'id'
			this.titleName = 'name'
		}
	},
	methods: {
		isSelected(data) {
			if (this.multiple) {
				if(this.nowValue && this.nowValue.length > 0){
					return this.nowValue.indexOf(data[this.keyName]) > -1
				}else if (data[this.keyName] == 0){
					return true
				}
			} else {
				return this.nowValue == data[this.keyName]
			}
		},
		change(data) {
			let result = null;
			if (this.multiple) {
				if(data[this.keyName] > 0){
					result = this.nowValue
				}else{
					result = []
				}
			} else {
				result = data[this.keyName]
			}
			this.setvalue(result)
		},
		clear() {
			if (this.multiple) {
				this.setvalue([])
			} else {
				this.setvalue(0)
			}
		},
		setvalue(data) {
			let value = this.value
			value[this.prop] = data
			this.$emit('input', value)
		}
	},
	computed: {
		isEmpty() {
			return !this.nowValue || this.nowValue.length == 0
		},
		nowValue() {
			return this.value[this.prop]
		}
	}
}
</script>

<style lang='less'>
	.active{
		color: @primary-color;
	}
	.list{
		padding: 5px;
		border-bottom:1px solid #ddd;
		text-align: left;
		font-size: 12px;
		color: #555;
		.active{
			color: #fff;
			background: @primary-color;
		}
		input{
			overflow:visible;
		}
	}
	.title{
		width: 100%;
		padding: 5px;
		font-size: 15px;
		text{
			float: right;
			padding: 0 15px;
			color: #ccc;
		}
	}
	.item{
		text-align: center;
		min-width: 80px;
		display: inline-block;
		margin: 5px;
		background: #eee;
		padding: 5px;
		border-radius: 2px;
	}
	.more{
		transform: scale(2,1);
		text-align: center;
		color: #ccc;
	}
</style>